<script setup>
import EmojiPicker from "vue3-emoji-picker";
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import {onMounted, ref} from "vue";
import {showToast} from "@/components/toasts/LoginRegToast.js";
import {userStore} from "@/stores/userStore.js";
import {getTime} from "@/utils/getFormatTime.js";
import {messageService} from "@/service/messageService.js";
import {onBeforeRouteUpdate, useRoute} from "vue-router";
import FileUploadPreview from "@/pages/chat/components/FileUploadPreview.vue";

const emit = defineEmits(["sendingMsg"])

const route = useRoute()
const msg = ref('')
const msgInputElement = ref()
const imgFiles = ref([])
const imgList = ref([])
const isVoiceChat = ref(false)
const isRecording = ref(false)
const showEmojiPicker = ref(false)
const emojiName = [
  "face-smile",
  "face-smile",
  "face-tired",
  "face-surprise",
  "face-smile-wink",
  "face-smile-beam",
  "face-sad-tear",
  "face-sad-cry",
  "face-rolling-eyes",
  "face-meh-blank",
  "face-meh",
  "face-laugh-wink",
  "face-laugh-squint",
  "face-laugh-beam",
  "face-laugh",
  "face-kiss-wink-heart",
  "face-kiss-beam",
  "face-kiss",
  "face-grin-wink",
  "face-grin-wide",
  "face-grin-tongue-wink",
  "face-grin-tongue-squint",
  "face-grin-tongue",
  "face-grin-tears",
  "face-grin-stars",
  "face-grin-squint-tears",
  "face-grin-squint",
  "face-grin-hearts",
  "face-grin-beam-sweat",
  "face-grin-beam",
  "face-grin",
  "face-grimace",
  "face-frown-open",
  "face-frown",
  "face-flushed",
  "face-dizzy",
  "face-angry",
  "face-tired",
  "face-surprise",
  "face-smile-wink",
  "face-smile-beam",
  "face-sad-tear",
  "face-sad-cry",
  "face-rolling-eyes",
  "face-meh-blank",
  "face-meh",
  "face-laugh-wink",
  "face-laugh-squint",
  "face-laugh-beam",
  "face-laugh",
  "face-kiss-wink-heart",
  "face-kiss-beam",
  "face-kiss",
  "face-grin-wink",
  "face-grin-wide",
  "face-grin-tongue-wink",
  "face-grin-tongue-squint",
  "face-grin-tongue",
  "face-grin-tears",
  "face-grin-stars",
  "face-grin-squint-tears",
  "face-grin-squint",
  "face-grin-hearts",
  "face-grin-beam-sweat",
  "face-grin-beam",
  "face-grin",
  "face-grimace",
  "face-frown-open",
  "face-frown",
  "face-flushed",
  "face-dizzy",
  "face-angry"
]
const randomlyEmojiNum = ref(0)
const recordingTime = ref(0)
let recordingTimer
let audioStream
let mediaRecorder
let audioURL

const props = defineProps({
  chatId: {
    required: true,
    type: String
  }
})

const handleDeleteAttach = (idx) => {
  imgList.value.splice(idx, 1)
  imgFiles.value.splice(idx, 1)
}


const handleMsgInput = () => {
  msg.value = msgInputElement.value.innerText
}

const handlePaste = (event) => {
  const items = event.clipboardData.items;
  for (const item of items) {
    if (item.type.startsWith('image/') || item.type.startsWith('video/') || item.type.startsWith('audio/')) {
      if (imgList.value.length === 5 ) {
        showToast('warning', '一次最多添加5个附件')
        break
      }

      const file = item.getAsFile();
      imgFiles.value.push(file)
      const reader = new FileReader();

      reader.onload = (e) => {
        imgList.value.push({
          base64: e.target.result,
          type: file.type,
          name: file.name
        })
      };
      reader.readAsDataURL(file);
    } else if (item.type.startsWith('text/')) {
      msgInputElement.value.innerText+= event.clipboardData.getData('text')
      msg.value+= event.clipboardData.getData('text')
      break
    } else {
      showToast('warning', '暂不支持此格式的文件')
    }
  }
}

const onSelectEmoji = (emoji) =>  {
  msg.value = msg.value+emoji.i
  showEmojiPicker.value = false
  msgInputElement.value.innerText+=emoji.i
  msgInputElement.value.focus()
}

const onSubmit = async () =>{
  if (imgFiles.value.length === 0) {
    if(msg.value === undefined || msg.value === null || msg.value.trim() === '') return false
  }
  await sendNewMsgToServer()
}

const sendNewMsgToServer = async (audioBlob) => {
  const msgData = ref({
    id: null,
    target: 'group',
    chat_id: props.chatId.trim(),
    sender_id: userStore().userInfo.id,
    text: msg.value,
    audio: audioBlob ?? null,
    file: imgFiles.value,
    send_time: getTime(),
    name: userStore().userInfo.name,
    avatar: userStore().userInfo.avatar,
    isOnSending: true,
  });

  msgInputElement.value.innerText = null
  msg.value = ''

  emit('sendingMsg', msgData.value)

  msgInputElement.value.innerText = ''
  imgList.value.length = 0

  const res = await messageService().sendMessage(msgData.value)
  if (res) {
    imgFiles.value.length = 0
    msgData.value.isOnSending = false
  }
};

onMounted(()=> {
  document.querySelector('.emojiCustom').addEventListener('mouseenter', ()=>{
    randomlyEmojiNum.value = Math.floor(Math.random()*72)
  })
})

// onBeforeRouteUpdate(async (to, from, next)=>{
//   chatId.value = to.params.chatId
//   next()
// })


// window.onkeydown = async (e) => {
//   if (isVoiceChat.value) {
//     if (e.code === 'Space') {
//       if(!isRecording.value) {
//         recordingTimer = setInterval(()=>{
//           recordingTime.value+=0.05
//         },50)
//         isRecording.value = true;
//         try {
//           audioStream = await navigator.mediaDevices.getUserMedia({ audio: true });
//           console.warn("已获取麦克风权限");
//           mediaRecorder = new MediaRecorder(audioStream)
//           mediaRecorder.ondataavailable = e =>{
//             if (e.data.size > 0 && recordingTime.value > 1) {
//               recordingTime.value = 0
//               const audioBlob = new Blob([e.data], { type: 'audio/ogg; codecs=opus' });
//               audioURL = URL.createObjectURL(audioBlob)
//             }
//           }
//           mediaRecorder.start();
//         } catch (error) {
//           showToast('error','无法获取获取麦克风权限')
//         }
//       }
//     }
//   }
// }
//
// window.onkeyup = async (e) => {
//   if (isVoiceChat.value) {
//     if (e.code === 'Space') {
//       isRecording.value = false;
//       clearInterval(recordingTimer)
//       if (recordingTime.value < 1) {
//         recordingTime.value = 0
//         console.log("时间太短")
//         stopRecording()
//       } else {
//         stopRecording()
//       }
//     }
//   }
// }

// function stopRecording() {
//   mediaRecorder.stop();
//   console.log('已停止录制')
//   if (audioStream) {
//     audioStream.getTracks().forEach(track => track.stop());
//     audioStream = null;
//   }
// }

// window.onkeyup = async (e) => {
//   if (isVoiceChat.value) {
//     if (e.code === 'Space') {
//       isRecording.value = false;
//       clearInterval(recordingTimer)
//       if (recordingTime.value < 1) {
//         recordingTime.value = 0
//         console.log("时间太短")
//         stopRecording()
//       } else {
//         stopRecording()
//       }
//     }
//   }
// }

</script>

<template>
  <form id="form">
    <div class="channelBottomBar">
      <div class="channelTextArea w-100 rounded-3 bg-secondary-subtle">
        <div class="scrollableContainer d-flex flex-column">
          <div class="uploadInput d-flex flex-wrap" ref="uploadListElement">
            <FileUploadPreview :files="imgList"/>
          </div>

          <div class="d-flex justify-content-between align-items-start">
            <div class="attachWrapper d-flex align-items-center">
              <font-awesome-icon class="fIcon" :icon="['fas', 'link']" />
            </div>
            <div class="textArea w-100">
              <div style="padding: 15px 0" v-show="!isVoiceChat">
                <div v-if="0" class="placeholderCustom position-absolute">SendMsg</div>
                <div
                    @paste.prevent="handlePaste"
                    class="textbox pe-2"
                    spellcheck="true"
                    @input="handleMsgInput"
                    @keydown.enter.prevent="onSubmit"
                    ref="msgInputElement"
                    contenteditable="true"
                >
                </div>
              </div>

              <div style="padding: 15px 0" class="text-center" v-show="isVoiceChat">
                <span>{{parseInt(recordingTime) === 0? '' : parseInt(recordingTime)+'s'}} {{ isRecording? '录制中，抬起发送' : '按下空格录制，抬起发送' }}</span>
              </div>

            </div>
            <div class="msgButtonDiv d-flex align-items-center">
              <div class="msgButton">
                <div class="d-flex align-items-center position-relative">
                  <font-awesome-icon @click="showEmojiPicker = !showEmojiPicker" class="fIcon emojiCustom" :icon="['fas', emojiName[randomlyEmojiNum]]"/>
                </div>
              </div>
              <div class="msgButton" @click="isVoiceChat=!isVoiceChat">
                <font-awesome-icon class="fIcon" :icon="['fas', 'microphone']" />
              </div>
            </div>
          </div>

        </div>
      </div>
      <div v-show="showEmojiPicker" @contextmenu.prevent="showEmojiPicker = !showEmojiPicker" @click.prevent="showEmojiPicker = !showEmojiPicker" class="emojiMusk"></div>
      <EmojiPicker
          v-show="showEmojiPicker"
          class="emojiPicker position-absolute animate__animated animate__fadeIn animate__faster"
          :native="true"
          @select="onSelectEmoji"
          :theme="userStore().userSetting.theme ? 'dark' : 'light'"
          :disable-skin-tones="true"
      />
    </div>
  </form>
</template>

<style scoped>
.emojiPicker {
  transform: translateY(-101%);
  right: 0;
  z-index: 1000;
}

.emojiMusk {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}
.channelBottomBar {
  position: relative;
  display: flex;
  flex-direction: row;
  border: 0;
  margin: 0;
  padding: 0;
  vertical-align: baseline;
}

.channelTextArea {
  margin-bottom: 24px;
  unicode-bidi: isolate;
}

.placeholderCustom {
  user-select: none;
}

.attachWrapper {
  top: 0;
  cursor: pointer;
  margin: 0 16px;
  height: 54px;
  position: sticky;
}

.msgButtonDiv {
  top: 0;
  height: 54px;
  position: sticky;
}

.msgButton {
  cursor: pointer;
  margin-right: 20px;
}

.scrollableContainer {
  max-height: calc(50vh - 14px);
  overflow-y: auto;
  width: 100%;
  min-width: 0;
}

.scrollableContainer::-webkit-scrollbar {
  width: 5px;
}

.textArea {
  width: 100%;
  min-width: 0;
}

.textbox {
  max-width: 100%;
  position: relative;
  outline: none;
  word-wrap: anywhere;
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

#form {
  position: relative;
  flex-shrink: 0;
  padding-left: 16px;
  padding-right: 16px;
}

#form>button {
  background: #333;
  border: none;
  padding: 0 1rem;
  margin: 0.25rem;
  border-radius: 3px;
  outline: none;
  color: #fff;
}

.emojiCustom {
  display: block;
  transition: all 100ms ease-in-out;
}
.emojiCustom:hover {
  transform: scale(1.2);
}

</style>